package com.zyl.pagergallerysave_java.fragment;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.zyl.pagergallerysave_java.R;
import com.zyl.pagergallerysave_java.adapter.GalleryAdapter;
import com.zyl.pagergallerysave_java.adapter.PhotoAdapter;

import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;


public class PhotoFragment extends Fragment {

    private ViewPager2 viewPager2;
    private TextView textViewNumber;
    private ImageView imageViewDownload;

    public static final int REQUEST_WRITE_EXTERNAL_STORAGE = 1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_photo, container, false);
        viewPager2 = view.findViewById(R.id.viewPager2);
        textViewNumber = view.findViewById(R.id.textViewNumber);
        imageViewDownload = view.findViewById(R.id.imageViewDownload);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        PhotoAdapter photoAdapter = new PhotoAdapter();

        final ArrayList photoList = getArguments().getParcelableArrayList(GalleryAdapter.PHOTO_LIST);
        photoAdapter.submitList(photoList);
        viewPager2.setAdapter(photoAdapter);
        viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                textViewNumber.setText(position + 1 + " / " + photoList.size());
            }
        });

        viewPager2.setCurrentItem(getArguments().getInt(GalleryAdapter.PHOTO_POSITION), false);
        viewPager2.setOrientation(ViewPager2.ORIENTATION_VERTICAL);
        imageViewDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT < 29 && ContextCompat.checkSelfPermission(requireContext(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    //本地方法，需要重写
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            REQUEST_WRITE_EXTERNAL_STORAGE);
                } else {
                    savePhoto();
                }
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_WRITE_EXTERNAL_STORAGE) {
            savePhoto();
        } else {
            Toast.makeText(requireContext(), "存储失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void savePhoto() {
//        bitmap.compress(Bitmap.CompressFormat.PNG, 100, openFileOutput("picture", Context.MODE_PRIVATE));
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
        RecyclerView recyclerView = (RecyclerView) viewPager2.getChildAt(0);
        PhotoAdapter.PhotoViewHolder holder = (PhotoAdapter.PhotoViewHolder) recyclerView.findViewHolderForAdapterPosition(viewPager2.getCurrentItem());

        Bitmap bitmap = ((BitmapDrawable) holder.photoView.getDrawable()).getBitmap();

        try {
            Uri saveUri = requireContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    new ContentValues());
            OutputStream outputStream = requireContext().getContentResolver().openOutputStream(saveUri);
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)) {
                Log.d("myTAG", "run: 存储成功");
                Toast.makeText(requireContext(), "存储成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(requireContext(), "存储失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Toast.makeText(requireContext(), "存储失败", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

//            }
//        }).start();
    }
}